package org.medicalinstrument.service;

import net.sf.json.JSONObject;
import org.medicalinstrument.bean.ProductVo;
import org.medicalinstrument.bean.RentCart;
import org.medicalinstrument.dao.RentCartDao;
import org.medicalinstrument.impl.RentCartDaoImpl;

import java.sql.SQLException;
import java.util.List;

/**
 * @Author: kongHuan
 * @Date: 2019/3/14 19:30
 * @Description:
 */
public class RentCartService {
    private String returnString;

    /**
     * @Author: kongHuan
     * @Date: 2019/3/14 19:32
     * @Description:添加租物车
     */
    RentCartDao dao = new RentCartDaoImpl();
    public String addAll(RentCart cart){
        try {
            if(dao.add(cart)){
                //returnString = "{\"state\":\"success\"}";
                returnString = "success";
            }

        } catch (SQLException e) {
            e.printStackTrace();
            returnString = "failed";
            //returnString = "{\"state\":\"failed\"}";
        }
        return returnString;
    }

    public String getByAccountNo(String accountNo) {
        RentCart cart = null;
        try {
            cart = dao.getByAccountNo(accountNo);
            if(cart.getProducts() != null && cart.getProducts().size() > 0){
                returnString = JSONObject.fromObject(cart).toString();
                //Gson gson = new Gson();
                //returnString = gson.toJson(cart);
                //System.out.println(returnString);
            }else{
                returnString = "emptyCart";
            }
        } catch (SQLException e) {
            //returnString = "error";
            e.printStackTrace();
        }
        return returnString;
    }

    public String deleteItem(String accountNo, List<ProductVo> products) {
        for(ProductVo product : products){
            try {
                dao.deleteRecored(accountNo,product.getProductQR());
                returnString = "success";
            } catch (SQLException e) {
                returnString = "failed";
                e.printStackTrace();
            }
        }
        System.out.println(returnString);
        return returnString;
    }

    public String getByPrimaryKey(String accountNo, String productQR) {
        ProductVo product = null;
        try {
            product  = dao.getByRecordAll(accountNo,productQR);
            if(product != null){
                returnString = JSONObject.fromObject(JSONObject.fromObject(product)).toString();
            }else{
                returnString = "select_fail";
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return returnString;
    }

    public String updateItem(RentCart cart) {
        try {
            if(dao.update(cart)){
                returnString = "update_success";
            }
        } catch (SQLException e) {
            returnString = "update_fail";
            e.printStackTrace();
        }
        return returnString;
    }
}
